import api from '../api/index.js'
var jweixin = require('jweixin-module')
let api_list = [
  'checkJsApi',
  'onMenuShareTimeline',
  'onMenuShareAppMessage',
  'hideOptionMenu',
  'showOptionMenu',
  'chooseWXPay',
  'updateAppMessageShareData',
  'updateTimelineShareData',
]
export default {
  // 判断是否在微信中
  isWechat() {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/micromessenger/i) == 'micromessenger') {
      return true
    } else {
      return false
    }
  },
  async getJSSDK() {
    let params = {
      SDK: api_list.toString(),
    }
    const res = await api.common.user('getJSSDK', params)
    if (res.code === 200) {
      return res.data
    }
  },

  // 初始化sdk配置
  async initJssdk(params, callback, url) {
    jweixin.config({
      debug: false,
      appId: params.appId,
      timestamp: params.timestamp,
      nonceStr: params.nonceStr,
      signature: params.signature,
      jsApiList: api_list,
    })
    // 配置完成后，再执行分享等功能
    if (callback) {
      callback()
    }
  },
  // 公众号支付
  startPay(params, order_id) {
    console.log(params)
    const { pay_info } = params
    if (!this.isWechat()) {
      return
    }
    this.initJssdk(pay_info, function () {
      jweixin.ready(function () {
        jweixin.chooseWXPay({
          nonceStr: pay_info.nonceStr,
          timestamp: pay_info.timestamp,
          package: pay_info.package,
          signType: pay_info.signType,
          paySign: pay_info.paySign,
          success: () => {
            uni.showToast({
              title: '支付成功',
              icon: 'success',
            })
            setTimeout(() => {
              location.reload()
            }, 1000)
          },
          fail: (err) => {
            uni.showToast({
              title: '支付失败',
              icon: 'none',
            })
            setTimeout(() => {
              location.reload()
            }, 1000)
          },
          cancel: (err) => {},
        })
      })
    })
  },
  // 在需要自定义分享的页面中调用
  share(data, url) {
    url = url ? url : window.location.href
    if (!this.isWechat()) {
      return
    }
    // 每次都需要重新初始化配置，才可以进行分享
    this.initJssdk(function () {
      jweixin.ready(function () {
        var shareData = {
          title: data && data.title ? data.title : '艺心造',
          desc: data && data.desc ? data.desc : '艺心造',
          link: url,
          imgUrl: data.img,
          success(res) {
            console.log(res)
          },
          cancel(res) {
            console.log(res)
          },
        }
        // 分享给朋友接口
        jweixin.updateAppMessageShareData(shareData)
        // 分享到朋友圈接口
        jweixin.updateTimelineShareData(shareData)
      })
    }, url)
  },
}
